package com.hellowx.qydcdev.controller;


import com.hellowx.qydcdev.annotaion.RequiredToken;
import com.hellowx.qydcdev.utils.OSSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created on 2022/1/12.
 *
 * @author Hello WX
 */
@Api(tags = "文件上传模块")
@RestController
@Slf4j
@RequestMapping("upload")
public class UploadController {

    @ApiOperation("上传图片")
    @PostMapping("/avatar")
    @RequiredToken
    public Map<String,Object> uploadImage(@RequestParam("file") MultipartFile file,
                                          HttpServletRequest request) throws IOException {
        //1.获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        log.info("接收文件名称: {}", originalFilename);
        log.info("文件大小为: {}", file.getSize());

        //2.获取文件后缀 mp4 avi ....
        String ext = FilenameUtils.getExtension(originalFilename);

        //3.生成uuid
        String uuidFileName = UUID.randomUUID().toString().replace("-", "");

        //4.生成uuid文件名名称
        String newFileName = uuidFileName + "." + ext;

        //5.上传阿里云oss 返回文件在oss地址
        String url = OSSUtils.upload(file.getInputStream(), "videos", newFileName);
        log.info("上传成功返回的地址: {}", url);

        Map<String, Object> map = new HashMap<>();
        map.put("flag",true);
        map.put("url",url);
        return map;
    }
}
